package com.fourhats.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fourhats.services.CategoryService;
import com.fourhats.services.MarketService;
import com.fourhats.services.ProductService;
import com.fourhats.services.QuestionService;
import com.fourhats.services.dto.SearchableEntity;

@Controller
public class HeaderController extends GenericController {

	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private MarketService marketService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private QuestionService questionService;
	
	@RequestMapping(value = "/header/getProductsAndMarketsByKeyword", 
	method = RequestMethod.GET, 
	headers="Accept=*/*")
	public @ResponseBody List<SearchableEntity> getProductsAndMarketsByKeyword(@RequestParam("term") String keyWord) {
		List<? extends SearchableEntity> categories = this.categoryService.getCategoriesByKeyword(keyWord);
		List<? extends SearchableEntity> markets = this.marketService.getMarketsByKeyword(keyWord);
		List<SearchableEntity> searchableEntities = new ArrayList<SearchableEntity>();
		searchableEntities.addAll(categories);
		searchableEntities.addAll(markets);
		
		return searchableEntities;
	}
	
	@RequestMapping(value="/search/{keyword}")
    public String goToProductAndMarketsSearch(@PathVariable String keyword, Model model) {
		model.addAttribute("keyword", keyword);
        return "content/productsAndMarkets";
    }
	
	@RequestMapping(value = "/header/hasUnvisitedSoldProducts", method = RequestMethod.GET, headers="Accept=*/*")
	public @ResponseBody boolean hasUnvisitedSoldProducts() {
		if(this.isUserLogged()) {
			return productService.hasUnvisitedSoldProducts(this.getUserId());
		} else {
			return false;
		}
	}
	
	@RequestMapping(value = "/header/hasUnvisitedQuestions", method = RequestMethod.GET, headers="Accept=*/*")
	public @ResponseBody boolean hasUnvisitedQuestions() {
		if(this.isUserLogged()) {
			return questionService.hasUnvisitedQuestions(this.getUserId());
		} else {
			return false;
		}
	}
}
